<?php

function loadDbSql($xmlfile) {
  $dom = new DomDocument;
  $dom->load( "../db/dbspec/${xmlfile}.xml" );
  
  $sql = "";
  foreach( $dom->getElementsByTagName( 'table' ) as $table ) {
    if( !$table->hasAttribute('name') )
      return false;
    else 
      $tname = $table->getAttribute('name');

    if( $table->hasAttribute('overwrite') ) {
      if( $table->getAttribute('overwrite') == true )
        $sql .= "DROP TABLE IF EXISTS ${tname};\r\n";
    }

    $sql .= "CREATE TABLE ${tname} ( \r\n\t";

    $tfields = array();
    foreach( $table->getElementsByTagName('field') as $field ) {
      if( $field->hasAttribute('type') ) 
        $fieldBuilder = 'dbBuilder_'.$field->getAttribute('type');
      else
        // XXX throw warning
        return false;

      $tfields[] = $fieldBuilder($field);
    }
    $sql .= implode( ", \r\n\t", $tfields );

    $sql .= " );\r\n";
  }

  return $sql;
}

function loadDbInset($xmlfile) {
  $dom = new DomDocument;
  $dom->load( "../db/dbdata/${xmlfile}.xml" );
  $sql = "";

}

function dbBuilder_int($field) {
  $frtn = '';

  if( $field->hasAttribute('name') )
    $frtn .= $field->getAttribute('name');
  else
    return false;

  $frtn .= ' INTEGER ';

  if( $field->hasAttribute('primary_key') ) {
    if( $field->getAttribute('primary_key') )
      $frtn .= ' PRIMARY KEY ';
  }

  if( $field->hasAttribute('null') ) {
    if( $field->getAttribute('null') ) 
      $frtn .= ' NULL ';
    else
      $frtn .= ' NOT NULL ';
  }

  return $frtn;
}
function dbBuilder_clob($field) {
  $frtn = '';

  if( $field->hasAttribute('name') )
    $frtn .= $field->getAttribute('name');
  else
    return false;

  $frtn .= ' CLOB ';

  if( $field->hasAttribute('null') ) {
    if( $field->getAttribute('null') ) 
      $frtn .= ' NULL ';
    else
      $frtn .= ' NOT NULL ';
  }

  return $frtn;
}
function dbBuilder_text($field) {
  $frtn = '';

  if( $field->hasAttribute('name') )
    $frtn .= $field->getAttribute('name');
  else
    return false;

  $frtn .= ' TEXT ';

  if( $field->hasAttribute('len') ) { 
    $frtn .= ' ('.$field->getAttribute('len').') ';
  } else {
    $frtn .= ' (255) ';
  }

  if( $field->hasAttribute('primary_key') ) {
    if( $field->getAttribute('primary_key') )
      $frtn .= ' PRIMARY KEY ';
  }

  if( $field->hasAttribute('unique') ) {
    if( $field->getAttribute('unique') ) 
      $frtn .= ' UNIQUE ';
  }

  if( $field->hasAttribute('null') ) {
    if( $field->getAttribute('null') ) 
      $frtn .= ' NULL ';
    else
      $frtn .= ' NOT NULL ';
  }

  return $frtn;
}

?>
